/**
 * Created by heqian on 17-7-5.
 */

var F;
(function () {
    var cfg = {
        lineCount: 10,
        faceMap: [
            ["[/吐]", "../img/1.gif"],
            ["[/花]", "../img/2.gif"],
            ["[/拜托]", "../img/3.gif"],
            ["[/呆]", "../img/4.gif"],
            ["[/投降]", "../img/5.gif"],
            ["[/亲]", "../img/6.gif"],
            ["[/安静]", "../img/7.gif"],
            ["[/冷汗]", "../img/8.gif"],
            ["[/酷]", "../img/9.gif"],
            ["[/钱]", "../img/10.gif"],
            ["[/闭嘴]", "../img/11.gif"],
            ["[/尴尬]", "../img/12.gif"],
            ["[/晕]", "../img/13.gif"],
            ["[/高兴]", "../img/14.gif"],
            ["[/偷笑]", "../img/15.gif"],
            ["[/砸头]", "../img/16.gif"],
            ["[/哭]", "../img/17.gif"],
            ["[/服]", "../img/18.gif"],
            ["[/不要]", "../img/19.gif"],
            ["[/愁]", "../img/20.gif"],
            ["[/鼻血]", "../img/21.gif"],
            ["[/装傻]", "../img/22.gif"],
            ["[/怒火]", "../img/23.gif"],
            ["[/疑问]", "../img/24.gif"],
            ["[/闪]", "../img/25.gif"],
            ["[/蒙圈]", "../img/26.gif"],
            ["[/心]", "../img/27.gif"],
            ["[/流汗]", "../img/28.gif"],
            ["[/打脸]", "../img/29.gif"],
            ["[/惊恐]", "../img/30.gif"],
            ["[/微笑]", "../img/31.gif"],
            ["[/邪恶]", "../img/32.gif"],
            ["[/大笑]", "../img/33.gif"],
            ["[/惊讶]", "../img/34.gif"],
            ["[/色]", "../img/35.gif"],
            ["[/萌]", "../img/36.gif"],
            ["[/人品]", "../img/37.gif"],
            ["[/坏笑]", "../img/38.gif"],
            ["[/媚眼]", "../img/39.gif"],
            ["[/鄙视]", "../img/40.gif"],
            ["[/拜托]", "../img/41.gif"],
            ["[/大哭]", "../img/42.gif"],
            ["[/睡觉]", "../img/43.gif"],
            ["[/拜拜]", "../img/44.gif"],
            ["[/屎]", "../img/45.gif"],
            ["[/难过]", "../img/46.gif"],
            ["[/可爱]", "../img/47.gif"],
            ["[/强]", "../img/48.gif"],
            ["[/发怒]", "../img/49.gif"],
            ["[/困]", "../img/50.gif"],
        ]
    }

    var scripts = $('script');
    var script = scripts[scripts.length - 1];
    var strJsPath = document.querySelector ? script.src : script.getAttribute("src", 4);
    strJsPath = strJsPath.substr(0, strJsPath.lastIndexOf('/') + 1);
    var times = null;
    var faceDiv = null;
    var face = function (obj, conf) {
        if (null == obj)
            throw "没有指定输入框";
        var ret = {
            textobj: obj,
            config: conf,
            faceMap: cfg.faceMap,
            range: null,
            onselectionchange: function () {
                if (window.getSelection) {
                    var sel = document.getSelection();
                    var parent = sel.baseNode;
                    while (null != parent) {
                        if (parent === ret.textobj) {
                            ret.range = sel.getRangeAt(0);
                            return;
                        }
                        parent = parent.parentElement;
                    }
                }
            },
            createFace: function () {
                var lineCount = (null != ret.config && null != ret.config.lineCount ) ? ret.config.lineCount : cfg.lineCount;
                ret.faceMap = (null != ret.config && null != ret.config.faceMap ) ? ret.config.faceMap : cfg.faceMap;

                var html = '<div class="clearfix heqian-face">';
                for (var y = 0; y <= Math.floor(ret.faceMap.length / lineCount); y++) {
                    var temp = ret.faceMap.length - y * lineCount;
                    html += '<ul class="clearfix ' + (temp <= lineCount ? "ul-bottom" : "") + '">';

                    for (var x = 0; x < ((temp > lineCount) ? lineCount : temp); x++) {
                        var item = ret.faceMap[y * lineCount + x];
                        html += '<li ' + (0 == x ? 'class="li-left"' : '') + ' title="' + item[0].substr(2, item[0].length - 3) + '">' +
                            '<img src="' + strJsPath + item[1] + '">' +
                            '</li>';
                    }
                    html += '</ul ">';
                }
                html += '</Div>'
                $('body').append(html);
                return $(".heqian-face");
            },
            onClick: function (e) {
                var cli = $(this).find('img');
                if (window.getSelection && (null == ret.config || null == ret.config.onFaceClick))
                    insertHTML(ret.textobj, ret.range, '<img src="' + cli.attr('src') + '">');

                if (null == ret.config || true === ret.config.autoClose)
                    ret.hide();

                if (null != ret.config && null != ret.config.onFaceClick)
                    ret.config.onFaceClick(cli.attr('title'), cli.attr('src'));
            },
            hide: function () {
                if (null != faceDiv) {
                    faceDiv.hide();
                    if (null != times)
                        clearTimeout(times);
                    times = null;
                }
            },
            show: function (obj) {
                if (0 == obj)
                    throw "没有调用对像"

                faceDiv = $(".heqian-face");
                if (0 == faceDiv.length)
                    faceDiv = ret.createFace();

                $('.heqian-face ul li').unbind("click");
                $('.heqian-face ul li').click(ret.onClick);
                document.onselectionchange = ret.onselectionchange;

                faceDiv.css('top', getTop(obj) + obj.offsetHeight);
                faceDiv.css('left', getLeft(obj));
                faceDiv.show();

                if (null != times)
                    clearTimeout(times);

                var timeCall = function () {
                    faceDiv.css('top', getTop(obj) + obj.offsetHeight);
                    faceDiv.css('left', getLeft(obj));
                    times = setTimeout(timeCall, 30);
                }
                times = setTimeout(timeCall, 30);
            },


        }

        return ret;
    };

    function insertHTML(dthis, range, html) {
        if (null == range) {
            $(dthis).html(dthis.innerHTML + html);
            return;
        }

        var sel = document.getSelection();
        range.deleteContents();
        var el = document.createElement('div');
        el.innerHTML = html;
        var frag = document.createDocumentFragment(), node, lastNode;
        while ((node = el.firstChild)) {
            lastNode = frag.appendChild(node);
        }

        range.insertNode(frag);
        if (lastNode) {
            range = range.cloneRange();
            range.setStartAfter(lastNode);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }

    function getTop(e) {
        var offset = e.offsetTop;
        if (e.offsetParent != null) offset += getTop(e.offsetParent);
        return offset;
    }

    function getLeft(e) {
        var offset = e.offsetLeft;
        if (e.offsetParent != null) offset += getLeft(e.offsetParent);
        return offset;
    }

    face.textToFace = function (text, faceMap) {
        if (null == faceMap)
            faceMap = cfg.faceMap;

        for (var key in faceMap) {
            text = text.replace(faceMap[key][0], '<img src="' + strJsPath + faceMap[key][1] + '">');
        }
        return text;
    }

    face.faceTotext = function (text, faceMap) {
        if (null == faceMap)
            faceMap = cfg.faceMap;

        for (var key in faceMap) {
            text = text.replace('<img src="' + strJsPath + faceMap[key][1] + '">', faceMap[key][0]);
        }
        return text;
    }

    F = face;
})();
